package com.cloud.bssp.thread;

import java.util.concurrent.TimeUnit;

/**
 * Description: WaitAndNotify
 * Create Date: 2020/8/19
 * Modified By：
 * Modified Date：
 * Why &amp; What is modified：
 * Copyright (C) 2020 mvtech.com.cn All Right Reserved.
 *
 * @author weirx
 * @version 1.0
 */
public class WaitAndNotify {

    /**
     * 吃了吗
     */
    static boolean EATEN_YET = false;

    static Object lock = new Object();

    public static void main(String[] args) {

        new Thread(() -> {
            synchronized (lock) {
                while (true) {
                    if (EATEN_YET) {
                        System.out.println(Thread.currentThread().getName() + ":我要开始写作业了！！");
                        break;
                    } else {
                        try {
                            System.out.println(Thread.currentThread().getName() + ":吃饭前我先玩一会儿！！");
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }, "小A").start();

        new Thread(() -> {
            synchronized (lock) {
                while (true) {
                    if (EATEN_YET) {
                        System.out.println(Thread.currentThread().getName() + ":我要去钓鱼了！！");
                        break;
                    } else {
                        try {
                            System.out.println(Thread.currentThread().getName() + ":吃饭前我先睡一会儿！！");
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }

        }, "爸爸").start();

        new Thread(() -> {
            synchronized (lock) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + ":开饭了！！");
                EATEN_YET = true;
                lock.notifyAll();
            }

        }, "妈妈").start();
    }

}
